package com.junglone.gateway.admin.web.controller;

import com.junglone.gateway.admin.common.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import com.junglone.gateway.admin.common.core.domain.AjaxResult;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * Description: 登录验证
 * 
 * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
 * @since 2021/04/04 00:23
 */
@Controller
public class SysLoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysLoginController.class);

    @Resource
    private Global global;

    @GetMapping("/login")
    public String login(Model model) {

        Mono<Global> monoGlobal = Mono.just(global);
        model.addAttribute("global", monoGlobal);
        return "login";
    }

    @PostMapping(value = "/logging")
    @ResponseBody
    public Mono<AjaxResult> ajaxLogin(ServerWebExchange exchange) {

        Mono<MultiValueMap<String, String>> formData = exchange.getFormData();

        return formData.flatMap(data -> {

            LOGGER.info("username ==== {}", data.get("username").get(0));
            LOGGER.info("password ==== {}", data.get("password").get(0));

            String strUserName = data.getFirst("username");
            String strPassword = data.getFirst("password");

            LOGGER.info("global.getDefaultUserName() ==== {}", global.getDefaultUserName());
            LOGGER.info("global.getDefaultPassword() ==== {}", global.getDefaultPassword());

            if (global.getDefaultUserName().equals(strUserName) && global.getDefaultPassword().equals(strPassword)) {
                return exchange.getSession().flatMap(session -> {
                    session.getAttributes().put("sessionFlag", strUserName);
                    return Mono.just(AjaxResult.success());
                });
            }

            LOGGER.info("Wrong username or password [username = {}, password = {}]", strUserName, strPassword);

            return Mono.just(AjaxResult.error());
        });

    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }
}
